from typing import List

from tortoise.expressions import Q
from app.core.redis_base import delete_keys
from app.core.crud import CRUDBase
from app.models.appointment import AppointmentSpace
from app.schemas.appointment import AppointmentSpaceCreate,AppointmentSpaceUpdate


class AppointmentSpaceController(CRUDBase[AppointmentSpace, AppointmentSpaceCreate, AppointmentSpaceUpdate]):
    def __init__(self):
        super().__init__(model=AppointmentSpace)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('sort')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def get_space_names(self, ids: List):
        search = Q(id__in=ids)
        data = list(await self.model.filter(search).values_list('name', flat=True))
        return data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self,request, obj_in: AppointmentSpaceCreate):
        await self.create(obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_update(self,request, obj_in: AppointmentSpaceUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_delete(self,request, data_id: int):
        await self.remove(id=data_id)
        await self.do_delete_redis(request)
        return True

    async def level_list(self,search: Q = Q()):
        objs = await self.model.filter(search).all().order_by('sort').values("id", "name")
        data = dict()
        for obj in objs:
            data[obj['id']] = obj['name']
        return data

    @staticmethod
    async def do_delete_redis(request):
        await delete_keys("appointment:space", request.state.redis)
        await delete_keys("dates:*", request.state.redis)
        await delete_keys("times:*", request.state.redis)
        await delete_keys("dates_ini:*", request.state.redis)
        await delete_keys("times_ini:*", request.state.redis)

appointment_space_controller =AppointmentSpaceController()
